package ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import util.CapsJdbc;
import util.CapsRes;
import util.CapsTableView;

import java.net.URL;
import java.util.*;

public class TeaMgr1 implements Initializable {

   @FXML
   private TextField tno;

   @FXML
   private TextField dno;

   @FXML
   private TextField name;
   
   @FXML
   private TextField Tea_tno;

   @FXML
   private TableView<Map<String,String>> teaTv;

   @FXML
   private void saveTea(ActionEvent event) {
      List<Object> params = new ArrayList<>(Arrays.asList(dno.getText(),name.getText(),tno.getText()));
      String updSql = "update tea set dno=?,name=? where tno=?";
      CapsRes capsRes = CapsJdbc.execSQL(updSql,params);
      if (capsRes.getTtlNum() < 1) {
         String addSql = "insert into tea(name,tno,dno) values(?,?,?)";
         CapsJdbc.execSQL(addSql,params);
      }
      this.dealQry(null);
   }
   
   @FXML
    private void qryByTea(ActionEvent event) {
      this.dealQry(Tea_tno.getText());
    }

   @Override
   public void initialize(URL url, ResourceBundle rb) {
     /* String strSQL = "select tno,dno,name from tea";
      CapsRes capsRes = CapsJdbc.execSQL(strSQL,null);
      CapsTableView.dealTableView(capsRes,teaTv);
      CapsTableView.addButtonToTable(teaTv,(recMap,idCol) -> {
         String delSql = "delete from tea where tno = ?";
         List<Object> params = new ArrayList<>(2);
         params.add(recMap.get("TNO"));
         CapsJdbc.execSQL(delSql,params);
      },(recMap,idCol) -> {
           tno.setText(recMap.get("TNO"));
           dno.setText(recMap.get("DNO"));
           name.setText(recMap.get("NAME"));
      });*/
	   this.dealQry(null);  
   }
   private void dealQry(String Tea_tno) {
	      teaTv.setItems(null);
	      teaTv.getColumns().clear();
	      String strSQL = "select tno,dno,name from tea";
	      List<Object> params = null;
	      if (null != Tea_tno && Tea_tno.length() > 0) {
	         strSQL += " where tno like ?";
	         params = new ArrayList<>(1);
	         params.add(Tea_tno+"%");
	      }
	      CapsRes capsRes = CapsJdbc.execSQL(strSQL,params);
	      CapsTableView.dealTableView(capsRes,teaTv);
	      CapsTableView.addButtonToTable(teaTv,(recMap,idCol) -> {
	         String delSql = "delete from tea where tno = ?";
	         List<Object> delParams = new ArrayList<>(1);
	         delParams.add(recMap.get("tno"));
	         CapsJdbc.execSQL(delSql,delParams);
	         this.dealQry(null);
	      },(recMap,idCol) -> {
	           tno.setText(recMap.get("tno"));
	           dno.setText(recMap.get("dno"));
	           name.setText(recMap.get("name"));
	      });
	   }
}
